package com.xdw.uploaddemo.service.impl;

import com.xdw.uploaddemo.model.UploadFile;
import com.xdw.uploaddemo.service.UploadFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class UploadFileServiceImpl implements UploadFileService {
    @Value("${fileUploadPathWindow}")
    private String fileUploadPathWindow;
    @Value("${fileUploadPathLinux}")
    private String fileUploadPathLinux;

    @Override
    public UploadFile uploadOne(String secondPath, MultipartFile file) throws IOException {
//上传目录地址
        //如果目录不存在，自动创建文件夹
        String os = System.getProperty("os.name");
        File dir = null;
        if (os.toLowerCase().contains("window")) {
            dir = new File(fileUploadPathWindow+ secondPath);
        } else {
            dir = new File(fileUploadPathLinux+ secondPath);
        }

        if (!dir.exists()) {
            dir.mkdir();
        }
        //文件后缀名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //上传文件名
        String filename = UUID.randomUUID() + suffix;
        //服务器端保存的文件对象
        File serverFile = null;
        if (os.toLowerCase().contains("window")) {
            serverFile = new File(fileUploadPathWindow + secondPath + filename);
        } else {
            serverFile = new File(fileUploadPathLinux +secondPath + filename);
        }
        //将上传的文件写入到服务器端文件内
        file.transferTo(serverFile);
        UploadFile uploadFile =new UploadFile();
        uploadFile.setFileOrginName(file.getOriginalFilename());
        uploadFile.setFilename(filename);
        uploadFile.setSuffix(suffix);
        return uploadFile;
    }

}
